## ---- geocode-venue-italy ----

library(sp)
library(rgeos)

load('replication_file_02_meetup_event_venue.RData')
load('replication_file_03_spatial_analysis.RData')

utm_crs <- '+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs'
camera_sp_utm <- spTransform(camera_sp, utm_crs)

meetup_venue <- meetup_venue[!duplicated(meetup_venue$venue_id),]
meetup_venue_it <- subset(meetup_venue, country %in% c("IT",'it'))

meetup_venue_it <- 
  SpatialPointsDataFrame(meetup_venue_it[,c('lon','lat')],
                         data = meetup_venue_it,
                         proj4string = CRS('+proj=longlat +datum=WGS84 +no_defs'))
utm_crs <- '+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs'
meetup_venue_it <- spTransform(meetup_venue_it, utm_crs)

library(parallel)
cl <- makeCluster(detectCores())
clusterExport(cl=cl, varlist=c("meetup_venue_it", "camera_sp_utm"))

res <- parLapply(cl, 1:nrow(meetup_venue_it), function(i)
  which.min(rgeos::gDistance(meetup_venue_it[i,], camera_sp_utm, byid=TRUE))
)

stopCluster(cl)

res_int <- unlist(res)
meetup_venue_it$minint_cod <- camera_sp_utm$minint_cod[res_int]
meetup_venue_it$istat_cod <- camera_sp_utm$istat_cod[res_int]
meetup_venue_it$istat_nom <- camera_sp_utm$istat_nom[res_int]

meetup_venue_it$uninom_cod <- camera_sp_utm$uninom_cod[res_int]
meetup_venue_it$uninom_nom <- camera_sp_utm$uninom_nom[res_int]

meetup_venue_it$regione <- camera_sp_utm$regione[res_int]

save(meetup_venue_it, 
     file = 'replication_file_04_geocode_event_venue.RData')

